//实现函数的call和apply，详解https://juejin.cn/post/6933413899215568903

Function.prototype.call2 = function(ctx) {
    ctx = ctx || globalThis
    let args = Array.from(arguments)
    args.shift()
    ctx.fn = this
    let res = ctx.fn(...args)
    delete ctx.fn
    return res
}

Function.prototype.apply2 = function(ctx, arr = []) {
    ctx = ctx || globalThis
    ctx.fn = this
    let res = ctx.fn(...arr)
    delete ctx.fn
    return res
}

let obj = {
    value: 1
}
globalThis.value = 'globalThis'
function foo(name, age){
    console.log(name, age)
    console.log(this.value)
    return 'foo'
}

console.log(foo.call2(null, 'sam', 18))
console.log(foo.apply2(obj, ['sam', 18]))